﻿using System;
using System.Net;
using SomeKit.Http;
using System.Collections.Generic;

#if WINDOWS_PHONE
using Microsoft.Phone.Reactive;
#else
using System.Linq;
#endif


namespace SomeKit.Rx.Http
{
    public static partial class HttpHelper
    {
        /// <summary>
        /// Creates a new WebHttpRequest instance for the specified uri <paramref name="uri"/> and returns an IObservable initialized to work with that instance. The delegate <paramref name="headerHandler"/> is invoked. 
        /// This is provided for the user, to be able to perform custom manipulation of the header, for ie. custom content- or accept-types or providing special security headers. 
        /// </summary>
        /// <param name="uri">The address of the resource, which is going to be fetched.</param>
        /// <param name="headerHandler">The delegate provided for custom header customization.</param>
        /// <returns>An IObservable of string</returns>
        public static IObservable<string> Get(this Uri uri, Action<HttpWebRequest> headerHandler = null)
        {
            var request = uri.GetRequest(SomeKit.Http.HttpHelper.Verbs.GET, headerHandler);
            return Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)().Select(r=>r.WebResponseAsString());
        }
        public static IObservable<string> GetXml(this Uri uri, Action<HttpWebRequest> headerHandler = null)
        {
            var request = uri.GetXmlRequest(SomeKit.Http.HttpHelper.Verbs.GET, false, headerHandler);
            return Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)().Select(r => r.WebResponseAsString());
        }
        public static IObservable<string> GetJson(this Uri uri, Action<HttpWebRequest> headerHandler = null)
        {
            var request = uri.GetJsonRequest(SomeKit.Http.HttpHelper.Verbs.GET, false, headerHandler);
            return Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)().Select(r => r.WebResponseAsString());
        }

        public static void ChainedGet(this Uri uri, IEnumerable<Uri> chainUris, Action<string> resultHandler, Action<Exception> errorHandler, Action allDone, Action<HttpWebRequest> headerHandler = null)
        {
            var head = uri.Get(headerHandler);
            foreach (var curi in chainUris)
            {
                head = head.Concat(curi.Get(headerHandler));
            }
            head.Subscribe(resultHandler,
                            errorHandler,
                            allDone
            );
        }
    }
}
